import {ADD_TODO, DEL_TODO, TOGGLE_TODO} from "../Action/ActionTypes";

import undoable,{distinctState} from 'redux-undo';//实现可撤销/恢复的todolist

//更新todos
/**
 * state = [{text:'',completed:false}]
 *
 * @param state
 * @param action
 * @returns {*}
 */
const todos = (state=[],action)=>{
    switch (action.type){
        case ADD_TODO:
            return [
                ...state,
                {
                    text:action.text,
                    completed:false
                }
            ]
        case TOGGLE_TODO:
            return state.map((todo,index)=>{
                if(index===action.index){
                    return Object.assign({},todo,{
                        completed:!todo.completed
                    })
                }
                return todo;
            })
        case DEL_TODO:
            let arr = [];
            [...state].map((todo,index)=>{
                if(index!==action.index){
                    arr.push(todo)
                }
                return arr
            })
            return arr;
        default:
            return state;
    }
}

const undoableTodos = undoable(todos,{
    filter: distinctState()
})

export default undoableTodos
